package com.test.webscoket.main;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Set;

@Component
public class RedisSessionManager {

    @Autowired
    private RedisTemplate redisTemplate;


    private static final String SESSION_PREFIX = "websocket:session:";


    // 存储会话信息
    public void storeSession(String clientId, String serverId) {
        String sessionKey = SESSION_PREFIX + clientId;
        long timestamp = System.currentTimeMillis();

        HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
        hashOps.put(sessionKey, "clientId", clientId);
        hashOps.put(sessionKey, "serverId", serverId);
        hashOps.put(sessionKey, "timestamp", String.valueOf(timestamp));
        hashOps.put(sessionKey, "status", "online");
    }

    // 获取会话信息
    public Map<String, String> getSession(String clientId) {
        String sessionKey = SESSION_PREFIX + clientId;
        return redisTemplate.opsForHash().entries(sessionKey);
    }

    // 删除会话信息
    public void deleteSession(String clientId) {
        String sessionKey = SESSION_PREFIX + clientId;
        redisTemplate.delete(sessionKey);
    }

    // 检查客户端是否在线
    public boolean isClientOnline(String clientId) {
        String sessionKey = SESSION_PREFIX + clientId;
        return redisTemplate.hasKey(sessionKey);
    }

    /**
     * 获取所有会话信息
     *
     * @return 包含所有会话信息的Map集合，键为会话ID，值为会话数据
     */
    public Set<String> getAllSessions(String deptId) {
        if (StrUtil.isNotBlank(deptId)){
            deptId =  deptId.substring(0, 8);
        }
        return redisTemplate.keys(SESSION_PREFIX + deptId + "*");
    }
}
